package com.summo.demo.exception.handler;

import javax.servlet.http.HttpServletResponse;

import com.summo.demo.exception.biz.BizException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

@RestControllerAdvice(basePackages = {"com.summo.demo.controller", "com.summo.demo.service"})
public class BizGlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public ModelAndView handler(BizException ex, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        switch (ex.getErrorCode()) {
            case LOGIN_USER_INFO_CHECK:
                // 重定向到登录页
                modelAndView.setViewName("redirect:/login");
                break;
            case NO_PERMISSIONS:
                // 设置错误信息和错误码
                modelAndView.addObject("errorMsg", ex.getErrorMsg());
                modelAndView.addObject("errorCode", ex.getErrorCode().getCode());
                modelAndView.setViewName("403");
                break;
            case BIZ_CHECK_FAIL:
            case BIZ_STATUS_ILLEGAL:
            case BIZ_QUERY_EMPTY:
            case SYSTEM_EXCEPTION:
            default:
                // 设置错误信息和错误码
                modelAndView.addObject("errorMsg", ex.getErrorMsg());
                modelAndView.addObject("errorCode", ex.getErrorCode().getCode());
                modelAndView.setViewName("error");
        }
        return modelAndView;
    }
}
